package servlet;

import Dao.IUserDao;
import Dao.UserDaoImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.UserService;
import service.UserServiceImpl;
import user.entity.User;

import java.io.IOException;
import java.io.PrintWriter;
//用户登录
@WebServlet(name="loginServlet",urlPatterns = "/loginServlet")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession httpSession= request.getSession();
        IUserDao iUserDao=new UserDaoImpl();
        PrintWriter out= response.getWriter();
        UserService userService=new UserServiceImpl();
        String num= request.getParameter("uNum");
        String name= request.getParameter("uName");
        String pwd= request.getParameter("uPwd");
        //注册页面传来的信息
        String num1= (String) httpSession.getAttribute("num");
        String name1= (String) httpSession.getAttribute("name");
        String pwd1= (String) httpSession.getAttribute("pwd");
        User user=userService.queryByNum(num);
        boolean result=iUserDao.IsExist(num);
        if(num.equals("") || name.equals("") || pwd.equals("")){
            out.print("<script>alert('需填写所有信息');window.location.href='index.jsp'</script>" );
        }else {
            if (result) {
                //数据库没有此人信息
                if(num.equals(num1)&&name.equals(name1)&&pwd.equals(pwd1))
                    out.print("<script>alert('登录成功，点击确定去报名');window.location.href='add.jsp'</script>" );

                else if(num1==null&&name1==null&&pwd1==null)
                    out.print("<script>alert('你的学号未被注册，去注册！');window.location.href='register.jsp'</script>" );
                else  out.print("<script>alert('信息有误！');window.location.href='index.jsp'</script>" );
            }
            else {
                if(num.equals(user.getNum()) && name.equals(user.getName()) && pwd.equals(user.getPassword())) {
                    httpSession.setAttribute("user4", user);
                    request.getRequestDispatcher("Info.jsp").forward(request, response);
                }
                else out.print("<script>alert('信息有误！');window.location.href='index.jsp'</script>");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
